<?php
class DateFieldBehavior extends CActiveRecordBehavior {

	public $displayFormat='d/M/yyyy';
	public $dataFormat='yyyy-M-d';
	public $dateField=array();

	private static $_formatter;

	public function beforeSave($event) {
		$model=$this->getOwner();
		$dateFields=is_array($this->dateField)?$this->dateField:array($this->dateField);
		foreach ($dateFields as $dateField){
			$timestamp=CDateTimeParser::parse($model->$dateField,$this->displayFormat,array('month'=>1,'day'=>1,'hour'=>0,'minute'=>0,'second'=>0));
			if($timestamp!==false)
			{
				$model->$dateField=$this->getFormatter()->format($this->dataFormat,$timestamp);
			}
		}
	}

	public function afterFind($event) {
		$model=$this->getOwner();
		$dateFields=is_array($this->dateField)?$this->dateField:array($this->dateField);
		foreach ($dateFields as $dateField){

			$timestamp=CDateTimeParser::parse($model->$dateField,$this->dataFormat,array('month'=>1,'day'=>1,'hour'=>0,'minute'=>0,'second'=>0));
			if($timestamp!==false)
			{
				$model->$dateField=$this->getFormatter()->format($this->displayFormat,$model->$dateField);
			}
		}
	}

	protected function getFormatter(){
		if(self::$_formatter!==null){
			return self::$_formatter;
		}
		self::$_formatter=Yii::app()->dateFormatter;
		return self::$_formatter;
	}
}